package model.schedule;

import model.database.CalendarWrapper;

public class AdHandler extends Thread {

	/**
	 * Time to sleep between auction end and the actual handling of the auction.
	 * Should not be neccessary, but used for dealing with out of sync clocks.
	 * Expressed in seconds.
	 */
	private final int timeOffset = 10;

	/**
	 * Maximum wait time. Will leave the ad un handled if more.
	 * Expressed in minutes.
	 */
	private final int timeGiveUpOffset = 10;
	private Ad ad;

	public AdHandler(Ad ad) {
		this.ad = ad;
	}

	public void run() {
		// Make sure the auction has really ended
		long timeDiff = 0;
		do {
			// Sleep until the next auction has come to an end
			CalendarWrapper timeNow = new CalendarWrapper();
			timeDiff = ad.getEnd().timeMillis() + timeOffset * 1000
					- timeNow.timeMillis();
			try {
				if (timeDiff > 0)
					if (timeDiff > timeGiveUpOffset * 60 * 1000)
						return;
					else
						Thread.sleep(timeDiff);
			} catch (InterruptedException e) {
				System.out.println("AdHandler interrupted while sleeping "+timeDiff+".");
				e.printStackTrace();
			}
		} while (timeDiff > 0);
		
		ad.handle();
	}
}
